package com.xu.system.service.db.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xu.system.mapper.SysUserDeptMapper;
import com.xu.system.model.entity.SysUserDept;
import com.xu.system.service.db.ISysUserDeptService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户和部门关联表 服务实现类
 * </p>
 *
 * @author 许乾伟
 * @since 2024-12-03 03:53:31
 */
@Service
public class SysUserDeptServiceImpl extends ServiceImpl<SysUserDeptMapper, SysUserDept> implements ISysUserDeptService {

    @Override
    public boolean saveUserDept(Long userId, Long deptId) {
        remove(new QueryWrapper<SysUserDept>().eq(SysUserDept.USER_ID, userId));
        if (deptId==null){
            return true;
        }
        return save(new SysUserDept().setUserId(userId).setDeptId(deptId));
    }

    @Override
    public Long getDeptIdByUserId(Long userId) {
        QueryWrapper<SysUserDept> wrapper = new QueryWrapper<>();
        wrapper.eq(SysUserDept.USER_ID, userId);
        SysUserDept sysUserDept = getOne(wrapper);
        if (sysUserDept == null){
            return null;
        }
        return sysUserDept.getDeptId();
    }

    @Override
    public List<Long> getDeptIdsByUserIds(List<Long> userIds) {
        QueryWrapper<SysUserDept> wrapper = new QueryWrapper<>();
        wrapper.in(SysUserDept.USER_ID, userIds);
        return list(wrapper).stream().map(SysUserDept::getDeptId).collect(Collectors.toList());
    }

    @Override
    public List<Long> getUserIdsByDeptId(Long deptId) {
        return list(new QueryWrapper<SysUserDept>()
                .eq(SysUserDept.DEPT_ID, deptId))
                .stream().map(SysUserDept::getUserId).collect(Collectors.toList());
    }

    @Override
    public Boolean isUse(Long deptId) {
        return count(new QueryWrapper<SysUserDept>().eq(SysUserDept.DEPT_ID, deptId)) > 0;
    }

    @Override
    public Map<Long, Integer> getUserCount(List<Long> deptIds) {
        QueryWrapper<SysUserDept> wrapper = new QueryWrapper<>();
        wrapper.in(SysUserDept.DEPT_ID, deptIds);
        List<SysUserDept> sysUserDeptList = list(wrapper);
        return sysUserDeptList.stream().collect(Collectors.groupingBy(SysUserDept::getDeptId, Collectors.summingInt(e -> 1)));
    }
}
